/* eslint-disable */
<template>
  <!-- 班级管理页面容器 -->
  <div class="classes-container">
    <!-- 页面标题和工具栏 -->
    <div class="page-header">
      <h3>班级管理</h3>
      <!-- 搜索和筛选区域 -->
      <div class="filter-area">
        <el-input
          v-model="searchQuery"
          placeholder="搜索班级"
          prefix-icon="el-icon-search"
          clearable
          style="width: 200px; margin-right: 15px;">
        </el-input>
        <el-select v-model="deptFilter" placeholder="选择院系" clearable @change="handleDeptChange" style="width: 200px; margin-right: 15px;">
          <el-option
            v-for="dept in departments"
            :key="dept.deptNumber"
            :label="dept.deptName"
            :value="dept.deptNumber">
          </el-option>
        </el-select>
        <el-button type="primary" @click="handleAdd">添加班级</el-button>
      </div>
    </div>

    <!-- 班级列表表格 -->
    <el-table :data="filteredClasses" style="width: 100%" v-loading="loading">
      <el-table-column prop="classId" label="班级ID" width="80"></el-table-column>
      <el-table-column prop="className" label="班级名称"></el-table-column>
      <el-table-column prop="grade" label="年级"></el-table-column>
      <el-table-column prop="majorName" label="专业名称"></el-table-column>
      <el-table-column prop="majorCode" label="专业代码"></el-table-column>
      <el-table-column prop="classNumber" label="班级号"></el-table-column>
      <el-table-column prop="deptName" label="所属院系"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="success" @click="handleAssignCourse(scope.row)">分配课程</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑班级对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="所属院系" prop="deptNumber">
          <el-select v-model="form.deptNumber" placeholder="请选择院系" style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.deptNumber"
              :label="dept.deptName"
              :value="dept.deptNumber">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%">
            <el-option label="2021级" value="2021"></el-option>
            <el-option label="2022级" value="2022"></el-option>
            <el-option label="2023级" value="2023"></el-option>
            <el-option label="2024级" value="2024"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称" prop="majorName">
          <el-input v-model="form.majorName"></el-input>
        </el-form-item>
        <el-form-item label="专业代码" prop="majorCode">
          <el-input v-model="form.majorCode"></el-input>
        </el-form-item>
        <el-form-item label="班级号" prop="classNumber">
          <el-input v-model="form.classNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配课程对话框 -->
    <el-dialog title="分配课程" :visible.sync="courseDialogVisible" width="60%">
      <div v-if="courseDialogVisible">
        <div class="course-assign-header">
          <h4>班级: {{ currentClass.className }}</h4>
          <div class="course-search">
            <el-input
              v-model="courseSearchQuery"
              placeholder="搜索课程"
              prefix-icon="el-icon-search"
              clearable
              style="width: 250px; margin-right: 15px;"
              @keyup.enter.native="searchCourses">
            </el-input>
            <el-button type="primary" @click="searchCourses">搜索</el-button>
          </div>
        </div>

        <!-- 已分配课程 -->
        <div class="assigned-courses" v-if="assignedCourses.length > 0">
          <h4>已分配课程</h4>
          <el-table :data="assignedCourses" style="width: 100%" border size="small">
            <el-table-column prop="courseId" label="课程ID" width="120"></el-table-column>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column prop="teacherName" label="任课教师"></el-table-column>
            <el-table-column prop="term" label="学期"></el-table-column>
            <el-table-column label="状态" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.status" placeholder="选择状态" size="small" @change="handleStatusChange(scope.row)">
                  <el-option label="未开始" value="未开始"></el-option>
                  <el-option label="进行中" value="进行中"></el-option>
                  <el-option label="已结束" value="已结束"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleRemoveCourse(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 可分配课程 -->
        <div class="available-courses">
          <h4>可分配课程</h4>
          <el-table :data="availableCourses" style="width: 100%" border size="small">
            <el-table-column prop="courseId" label="课程ID" width="120"></el-table-column>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column prop="description" label="课程描述" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button size="mini" type="success" @click="handleAssignCourseToClass(scope.row)">分配</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 选择教师对话框 -->
    <el-dialog title="选择任课教师" :visible.sync="teacherDialogVisible" width="40%" append-to-body>
      <el-form :model="courseAssignForm" label-width="100px">
        <el-form-item label="课程">
          <span>{{ selectedCourse.courseName }}</span>
        </el-form-item>
        <el-form-item label="任课教师" prop="teacherId">
          <el-select v-model="courseAssignForm.teacherId" placeholder="请选择教师" style="width: 100%">
            <el-option
              v-for="teacher in filteredTeachers"
              :key="teacher.teacherId"
              :label="teacher.name"
              :value="teacher.teacherId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="term">
          <el-select v-model="courseAssignForm.term" placeholder="请选择学期" style="width: 100%">
            <el-option label="2024春季学期" value="2024春季学期"></el-option>
            <el-option label="2024秋季学期" value="2024秋季学期"></el-option>
            <el-option label="2025春季学期" value="2025春季学期"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="teacherDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAssignCourse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAllDepartments, 
  getClassesByDepartment, 
  getAllClasses, 
  addClass, 
  updateClass, 
  deleteClass,
  getAllCourses,
  searchCourses,
  getAllTeachers,
  getTeachersByDepartment,
  getCoursesByClassId,
  assignCourseToClass,
  removeCourseFromClass,
  updateClassCourseStatus
} from '@/api/admin'

export default {
  name: 'AdminClasses',
  data() {
    return {
      // 加载状态
      loading: false,
      // 院系列表数据
      departments: [],
      // 班级列表数据
      classes: [],
      // 搜索关键词
      searchQuery: '',
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 院系筛选
      deptFilter: '',
      // 表单数据
      form: {
        deptNumber: '',
        grade: '',
        majorName: '',
        majorCode: '',
        classNumber: ''
      },
      // 表单验证规则
      rules: {
        deptNumber: [
          { required: true, message: '请选择所属院系', trigger: 'change' }
        ],
        grade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ],
        majorCode: [
          { required: true, message: '请输入专业代码', trigger: 'blur' }
        ],
        classNumber: [
          { required: true, message: '请输入班级号', trigger: 'blur' }
        ]
      },
      // 课程分配对话框
      courseDialogVisible: false,
      // 当前选中的班级
      currentClass: {},
      // 已分配课程
      assignedCourses: [],
      // 可分配课程
      availableCourses: [],
      // 课程搜索关键词
      courseSearchQuery: '',
      // 选择教师对话框
      teacherDialogVisible: false,
      // 教师列表
      teachers: [],
      // 选中的课程
      selectedCourse: {},
      // 课程分配表单
      courseAssignForm: {
        teacherId: '',
        term: '2024春季学期'
      }
    }
  },
  computed: {
    // 过滤后的班级列表
    filteredClasses() {
      if (!this.searchQuery) {
        return this.classes
      }
      
      const query = this.searchQuery.toLowerCase()
      return this.classes.filter(item => {
        return item.className?.toLowerCase().includes(query) ||
               item.majorName?.toLowerCase().includes(query) ||
               item.majorCode?.toLowerCase().includes(query) ||
               item.deptName?.toLowerCase().includes(query) ||
               item.grade?.toLowerCase().includes(query)
      })
    },
    
    // 根据当前班级院系过滤的教师列表
    filteredTeachers() {
      if (!this.currentClass || !this.currentClass.deptNumber) {
        return this.teachers;
      }
      
      // 只显示同一院系的教师
      return this.teachers.filter(teacher => 
        teacher.deptNumber === this.currentClass.deptNumber
      );
    }
  },
  // 组件创建时获取院系列表和所有班级
  created() {
    this.fetchDepartments()
    this.fetchAllClasses()
  },
  methods: {
    // 获取院系列表
    async fetchDepartments() {
      try {
        const response = await getAllDepartments()
        if (response.code === 200) {
          this.departments = response.data
        } else {
          this.$message.error(response.message || '获取院系列表失败')
        }
      } catch (error) {
        console.error('获取院系列表失败:', error)
        this.$message.error('获取院系列表失败')
      }
    },
    
    // 获取所有班级列表
    async fetchAllClasses() {
      this.loading = true
      try {
        const response = await getAllClasses()
        if (response.code === 200) {
          // 获取班级数据
          const classes = response.data || []
          
          // 如果有院系数据，则关联院系名称
          if (this.departments.length > 0) {
            // 创建院系编号到院系名称的映射
            const deptMap = {}
            this.departments.forEach(dept => {
              deptMap[dept.deptNumber] = dept.deptName
            })
            
            // 为每个班级添加所属院系名称
            classes.forEach(cls => {
              cls.deptName = deptMap[cls.deptNumber] || '未知院系'
            })
          } else {
            // 如果还没有院系数据，先获取院系数据
            await this.fetchDepartments()
            
            // 再次尝试关联院系名称
            const deptMap = {}
            this.departments.forEach(dept => {
              deptMap[dept.deptNumber] = dept.deptName
            })
            
            classes.forEach(cls => {
              cls.deptName = deptMap[cls.deptNumber] || '未知院系'
            })
          }
          
          this.classes = classes
        } else {
          this.$message.error(response.message || '获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
        this.$message.error('获取班级列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 获取某个院系的班级列表
    async fetchClasses(deptNumber) {
      this.loading = true
      try {
        const response = await getClassesByDepartment(deptNumber)
        if (response.code === 200) {
          const classes = response.data || []
          
          // 查找当前院系信息
          const dept = this.departments.find(d => d.deptNumber === deptNumber)
          const deptName = dept ? dept.deptName : '未知院系'
          
          // 为所有班级添加院系名称
          classes.forEach(cls => {
            cls.deptName = deptName
          })
          
          this.classes = classes
        } else {
          this.$message.error(response.message || '获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
        this.$message.error('获取班级列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 处理院系筛选变化
    handleDeptChange(value) {
      if (value) {
        this.fetchClasses(value)
      } else {
        this.fetchAllClasses()
      }
    },
    
    // 处理添加班级
    handleAdd() {
      this.dialogTitle = '添加班级'
      this.form = {
        deptNumber: this.deptFilter || '',
        grade: '',
        majorName: '',
        majorCode: '',
        classNumber: ''
      }
      this.dialogVisible = true
    },
    
    // 处理编辑班级
    handleEdit(row) {
      this.dialogTitle = '编辑班级'
      this.form = { ...row }
      this.dialogVisible = true
    },
    
    // 处理删除班级
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该班级吗？该操作不可逆', '提示', {
          type: 'warning'
        })
        
        const response = await deleteClass(row.classId)
        
        if (response.code === 200) {
          this.$message.success('删除班级成功')
          // 更新班级列表
          if (this.deptFilter) {
            this.fetchClasses(this.deptFilter)
          } else {
            this.fetchAllClasses()
          }
        } else {
          this.$message.error(response.message || '删除班级失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除班级失败:', error)
          this.$message.error('删除班级失败')
        }
      }
    },
    
    // 处理表单提交
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.$message.info('正在提交...')
            let response
            
            if (this.dialogTitle === '添加班级') {
              response = await addClass(this.form)
            } else {
              // 编辑班级
              response = await updateClass(this.form.classId, this.form)
            }
            
            if (response.code === 200) {
              this.$message.success(this.dialogTitle === '添加班级' ? '添加班级成功' : '更新班级成功')
              this.dialogVisible = false
              
              // 更新班级列表
              if (this.deptFilter) {
                this.fetchClasses(this.deptFilter)
              } else {
                this.fetchAllClasses()
              }
            } else {
              this.$message.error(response.message || '操作失败')
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败: ' + (error.message || '未知错误'))
          }
        } else {
          this.$message.warning('请完善表单信息')
          return false
        }
      })
    },

    // 处理分配课程
    async handleAssignCourse(row) {
      this.currentClass = row
      this.courseDialogVisible = true
      this.courseSearchQuery = ''
      
      // 加载班级已分配的课程
      await this.fetchAssignedCourses(row.classId)
      
      // 加载可分配的课程
      await this.fetchAvailableCourses()
    },

    // 获取班级已分配的课程
    async fetchAssignedCourses(classId) {
      try {
        this.$message.info('正在获取班级已分配课程...');
        console.log('正在获取班级ID为', classId, '的课程');
        const response = await getCoursesByClassId(classId);
        console.log('API响应:', response);
        
        if (response && response.code === 200) {
          this.assignedCourses = response.data || [];
          console.log('成功获取班级课程:', this.assignedCourses);
        } else {
          this.assignedCourses = [];
          const errMsg = response ? response.message || '未知错误' : '返回数据格式错误';
          console.error('获取已分配课程失败:', errMsg);
          this.$message.error('获取已分配课程失败: ' + errMsg);
        }
      } catch (error) {
        this.assignedCourses = [];
        console.error('获取已分配课程异常:', error);
        this.$message.error('获取已分配课程失败: ' + (error.message || '未知错误'));
      }
    },

    // 获取可分配的课程
    async fetchAvailableCourses() {
      try {
        console.log('正在获取所有课程列表');
        const response = await getAllCourses();
        console.log('获取课程列表响应:', response);
        
        if (response.code === 200) {
          // 过滤已分配的课程
          const assignedCourseIds = this.assignedCourses.map(c => c.courseId);
          console.log('已分配课程IDs:', assignedCourseIds);
          
          this.availableCourses = response.data.filter(course => 
            !assignedCourseIds.includes(course.courseId)
          );
          console.log('可分配课程列表:', this.availableCourses);
        } else {
          this.availableCourses = [];
          this.$message.error('获取可分配课程失败: ' + (response.message || '未知错误'));
        }
      } catch (error) {
        this.availableCourses = [];
        console.error('获取可分配课程失败:', error);
        this.$message.error('获取可分配课程失败: ' + (error.message || '未知错误'));
      }
    },

    // 搜索课程
    async searchCourses() {
      if (!this.courseSearchQuery.trim()) {
        await this.fetchAvailableCourses()
        return
      }

      try {
        const response = await searchCourses(this.courseSearchQuery.trim())
        if (response.code === 200) {
          // 过滤已分配的课程
          const assignedCourseIds = this.assignedCourses.map(c => c.courseId)
          this.availableCourses = response.data.filter(course => 
            !assignedCourseIds.includes(course.courseId)
          )
        } else {
          this.$message.error('搜索课程失败')
        }
      } catch (error) {
        console.error('搜索课程失败:', error)
        this.$message.error('搜索课程失败')
      }
    },

    // 处理分配课程到班级
    async handleAssignCourseToClass(course) {
      this.selectedCourse = course
      this.courseAssignForm = {
        teacherId: '',
        term: '2024春季学期'
      }
      
      // 获取教师列表，根据班级所在院系筛选
      await this.fetchTeachersByDept();
      
      // 显示选择教师对话框
      this.teacherDialogVisible = true
    },

    // 获取教师列表
    async fetchTeachers() {
      try {
        const response = await getAllTeachers()
        if (response.code === 200) {
          this.teachers = response.data
        } else {
          this.teachers = []
          this.$message.error('获取教师列表失败')
        }
      } catch (error) {
        this.teachers = []
        console.error('获取教师列表失败:', error)
        this.$message.error('获取教师列表失败')
      }
    },
    
    // 根据院系获取教师列表
    async fetchTeachersByDept() {
      try {
        if (!this.currentClass || !this.currentClass.deptNumber) {
          await this.fetchTeachers();
          return;
        }
        
        const deptNumber = this.currentClass.deptNumber;
        this.$message.info(`正在获取院系 ${this.currentClass.deptName} 的教师列表...`);
        const response = await getTeachersByDepartment(deptNumber);
        
        if (response.code === 200) {
          this.teachers = response.data;
          console.log(`获取到院系 ${this.currentClass.deptName} 的 ${this.teachers.length} 名教师`);
        } else {
          this.teachers = [];
          this.$message.error('获取院系教师列表失败');
          // 如果获取失败，则尝试获取所有教师
          await this.fetchTeachers();
        }
      } catch (error) {
        this.teachers = [];
        console.error('获取院系教师列表失败:', error);
        this.$message.error('获取院系教师列表失败，将显示所有教师');
        // 如果出错，则尝试获取所有教师
        await this.fetchTeachers();
      }
    },

    // 确认分配课程
    async confirmAssignCourse() {
      if (!this.courseAssignForm.teacherId) {
        this.$message.warning('请选择任课教师');
        return;
      }

      try {
        const data = {
          classId: this.currentClass.classId,
          courseId: this.selectedCourse.courseId,
          teacherId: this.courseAssignForm.teacherId,
          term: this.courseAssignForm.term,
          status: '未开始'
        };

        console.log('正在分配课程，请求数据:', data);
        const response = await assignCourseToClass(data);
        console.log('分配课程响应:', response);

        if (response && response.code === 200 && response.data === true) {
          this.$message.success('课程分配成功');
          this.teacherDialogVisible = false;
          
          // 刷新已分配课程
          await this.fetchAssignedCourses(this.currentClass.classId);
          
          // 刷新可分配课程
          await this.fetchAvailableCourses();
        } else {
          const errMsg = response ? response.message || '未知错误' : '返回数据格式错误';
          this.$message.error('课程分配失败: ' + errMsg);
        }
      } catch (error) {
        console.error('课程分配失败:', error);
        this.$message.error('课程分配失败: ' + (error.message || '未知错误'));
      }
    },

    // 处理移除课程
    async handleRemoveCourse(course) {
      try {
        await this.$confirm(`确认从班级移除课程 ${course.courseName}?`, '提示', {
          type: 'warning'
        })
        
        console.log('正在移除课程:', course);
        // 确保courseId是字符串类型
        const courseId = String(course.courseId);
        
        const response = await removeCourseFromClass(this.currentClass.classId, courseId);
        console.log('移除课程响应:', response);
        
        if (response && response.code === 200 && response.data === true) {
          this.$message.success('课程移除成功');
          
          // 刷新已分配课程
          await this.fetchAssignedCourses(this.currentClass.classId);
          
          // 刷新可分配课程
          await this.fetchAvailableCourses();
        } else {
          const errMsg = response ? response.message || '未知错误' : '返回数据格式错误';
          this.$message.error('课程移除失败: ' + errMsg);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('课程移除失败:', error);
          this.$message.error('课程移除失败: ' + (error.message || '未知错误'));
        }
      }
    },

    // 处理课程状态变更
    handleStatusChange(course) {
      // 构建更新数据
      const courseData = {
        courseId: course.courseId,
        classId: this.currentClass.classId,
        status: course.status
      };
      
      // 调用API更新课程状态
      updateClassCourseStatus(courseData)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('课程状态已更新');
          } else {
            this.$message.error(response.message || '状态更新失败');
            // 如果更新失败，回滚状态
            this.refreshAssignedCourses();
          }
        })
        .catch(error => {
          console.error('更新课程状态失败:', error);
          this.$message.error('状态更新失败，请重试');
          this.refreshAssignedCourses();
        });
    },
    
    // 刷新已分配课程列表
    refreshAssignedCourses() {
      if (this.currentClass && this.currentClass.classId) {
        this.loading = true;
        getCoursesByClassId(this.currentClass.classId)
          .then(response => {
            this.assignedCourses = response.data || [];
            this.loading = false;
          })
          .catch(error => {
            console.error('获取已分配课程失败:', error);
            this.loading = false;
          });
      }
    }
  }
}
</script>

<style scoped>
/* 班级管理页面容器样式 */
.classes-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

/* 页面标题和工具栏样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 页面标题样式 */
.page-header h3 {
  margin: 0;
}

/* 筛选区域样式 */
.filter-area {
  display: flex;
  align-items: center;
}

/* 空数据提示样式 */
.empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px 0;
  font-size: 14px;
}

/* 课程分配对话框样式 */
.course-assign-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.assigned-courses,
.available-courses {
  margin-bottom: 20px;
}

.assigned-courses h4,
.available-courses h4 {
  margin-bottom: 10px;
  font-weight: bold;
  color: #303133;
}
</style> 